package org.jeecg.modules.xxgx.common.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class CommonUtil {



    public static String UnFormartMoney(String moneyFormartString) {
        return moneyFormartString.replaceAll(",", "");
    }

    /**
     * 替换集合中每个Map的每个属性的值中逗号为空串
     */
    public static List<Map> replaceLDhOfList(List<Map> list) {
        //遍历集合，去掉每个字段值中的逗号
        for (int i = 0; i < list.size(); i++) {
            Set<String> keys = list.get(i).keySet();
            for (String key : keys) {
                if (list.get(i).get(key) != null) {
                    list.get(i).put(key, CommonUtil.UnFormartMoney(list.get(i).get(key).toString()));
                }
            }
        }
        return list;
    }


    //替换Map的每个属性的值中逗号为空串
    public static Map replaceLDhOfMap(Map map) {
        Set<String> keys = map.keySet();
        for (String key : keys) {
            if (map.get(key) != null) {
                map.put(key, CommonUtil.UnFormartMoney(map.get(key).toString()));
            }
        }
        return map;
    }

    //替换Map的每个属性的值中逗号为空串,除附件列表和名称
    public static Map replaceJtyjLDhOfMap(Map map) {
        Set<String> keys = map.keySet();
        for (String key : keys) {
            if (map.get(key) != null) {
                if (!("ZZPZH".equals(key) || "ZZPZFJ".equals(key))) {
                    map.put(key, CommonUtil.UnFormartMoney(map.get(key).toString()));
                }
            }
        }
        return map;
    }

    //把JSON字符串转换成List<Map>对象
    public static List JsonStringToList(String jsonStr) {
        List<Map> list = JSON.parseArray(jsonStr, Map.class);
        for (Map map : list) {
            Set<String> keys = map.keySet();
            for (String key : keys) {

                if (map.get(key) == null || "".equals(map.get(key).toString().trim())) {
                    map.put(key, null);
                }
            }
        }
        return list;
    }

    //复制map1中的值到另一个map2
    public static void copyMap(Map map1, Map map2) {
        for (Iterator it = map1.keySet().iterator(); it.hasNext(); ) {
            String key = it.next().toString();
            map2.put(key, map1.get(key));
        }
    }

    //导入数据处理
    public static void handle(List<Map> list) {
        for (Map<String, String> map : list) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String mapValue = entry.getValue();
                if ("undefined".equals(mapValue)) {
                    map.put(entry.getKey(), null);
                }
            }
        }
    }

    //根据年和月，查询此月有多少天  2019-8-27 14:14:17
    public static int getDaysByYearMonth(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }





    /**
     * rdd
     * 根据map中几个字段对list<map>进行分组 2020-3-27 08:56:09
     *
     * @param groupParam 需要通过哪些字段进行分组
     * @param listParam  需要被分组的list
     * @return
     */
    public static Map getListByGroup(List groupParam, List<Map> listParam) {
        Map<String, List<Map>> groupMap = new LinkedHashMap<>();

        for (int i = 0; i < listParam.size(); i++) {
            Map paramMap = listParam.get(i);
            String paramStr = "";
            for (int m = 0; m < groupParam.size(); m++) {
                paramStr += paramMap.get(groupParam.get(m));
            }
            if (groupMap.get(paramStr) != null) {
                List<Map> tempList = groupMap.get(paramStr);
                tempList.add(paramMap);
                groupMap.put(paramStr, tempList);
            } else {
                List<Map> tempList = new ArrayList<>();
                tempList.add(paramMap);
                groupMap.put(paramStr, tempList);
            }
        }
        return groupMap;
    }

    //根据request头判断客户端浏览器类型 2020-4-22 11:16:59 rdd
    public static String getUserAgent(HttpServletRequest request) {
        String userAgentRtn = "";

        // 获取请求头：user-agent
        String userAgent = request.getHeader("user-agent");

        // 判断用户使用的浏览器类型
        if (userAgent.contains("Firefox")) {
            userAgentRtn = "Firefox";
        } else if (userAgent.contains("Chrome")) {
            userAgentRtn = "Chrome";
        } else if (userAgent.contains("Trident")) {
            userAgentRtn = "IE";
        }
        return userAgentRtn;
    }

    /**
     * Map转String，转换成{key1 : value1, key1 : value1, key1 : value1, ...}
     *
     * @param map
     * @return
     */
    public static String getMapToString(Map<String, Object> map) {
        Set<String> keySet = map.keySet();
        //将set集合转换为数组
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        //给数组排序(升序)
        Arrays.sort(keyArray);
        //因为String拼接效率会很低的，所以转用StringBuilder
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (int i = 0; i < keyArray.length; i++) {
            // 参数值为空，则不参与签名 这个方法trim()是去空格
            if ((String.valueOf(map.get(keyArray[i]))).trim().length() > 0) {
                sb.append(keyArray[i]).append(":").append(String.valueOf(map.get(keyArray[i])).trim());
            }
            if (i != keyArray.length - 1) {
                sb.append(",");
            }
        }
        sb.append("}");
        return sb.toString();
    }

    /**
     * String转map
     *
     * @param str
     * @return
     */
    public static Map<String, Object> getStringToMap(String str) {
        //根据逗号截取字符串数组
        String[] str1 = str.split(",");
        //创建Map对象
        Map<String, Object> map = new HashMap<>();
        //循环加入map集合
        for (int i = 0; i < str1.length; i++) {
            //根据":"截取字符串数组
            String[] str2 = str1[i].split(":");
            //str2[0]为KEY,str2[1]为值
            map.put(str2[0], str2[1]);
        }
        return map;
    }

    //Double类型数据使用java正则表达式去掉多余的.与0
    public static double subZeroAndDot(double d) {
        String s = String.valueOf(d);
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
            d = Double.valueOf(s);
        }
        return d;
    }

    public static JSONObject toJsonObj(Map<String, Object> map, JSONObject resultJson) {
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            resultJson.put(key, map.get(key));
        }
        return resultJson;
    }

    //格式化日期字符串
    public static String formatStrDate(String str) {
        str = str.substring(0, 4) + "-" + str.substring(4, 6) + "-" + str.substring(6, 8);
        return str;
    }

    //list去重
    public static List<String> delRepeat(List<String> list) {
        List<String> listNew = new ArrayList<String>();
        for (String str : list) {
            if (!listNew.contains(str)) {
                listNew.add(str);
            }
        }
        return listNew;
    }

    //将map集合中的某个BigDecimal或double类型变量转换为BigDecimal
    public static BigDecimal convertBigDecimal(Map map, String param) {
        BigDecimal bg = new BigDecimal("0");
        if(map.get(param)==null){
            return bg;
        }
        if ("java.lang.Double".equals(map.get(param).getClass().getName())) {
            bg = BigDecimal.valueOf((double) map.get(param));
        } else if ("java.math.BigDecimal".equals(map.get(param).getClass().getName())) {
            bg = (BigDecimal) map.get(param);
        } else if ("java.lang.String".equals(map.get(param).getClass().getName())) {
            bg = new BigDecimal((String) map.get(param));
        }

        return bg;
    }

    /***
     *@Author zhoushaozhi
     *@Description 判断List对象是否为null或者空对象
     *@Date 2021/5/19 14:33
     *@param list
     *@Return boolean
     */
    public static boolean isNullOrEmpty(List list) {
        if (list == null || list.isEmpty()) {
            return true;
        }
        return false;
    }

    /***
     *@Author zhoushaozhi
     *@Description 对象转字符串
     *@Date 2022/7/28 17:54
     *@param obj
     *@Return String
     */
    public static String getObjectToString(Object obj) {
        if (obj == null) {
            return "";
        }
        return obj.toString();
    }


    /***
     *@Author zhoushaozhi
     *@Description map转实体
     *@Date 2021/5/24 10:26
     *@param type map
     *@Return Object
     */
    public static Object convertMapToEntity(Class type, Map map) throws Exception {
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        Object obj = type.newInstance();
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            String propertyName = descriptor.getName();
            if (map.containsKey(propertyName)) {
                Object value = map.get(propertyName);
                String descriptorTypeName = descriptor.getPropertyType().getName();
                if ("int".equalsIgnoreCase(descriptorTypeName)) {
                    descriptor.getWriteMethod().invoke(obj, Integer.parseInt((String) value));
                } else {
                    descriptor.getWriteMethod().invoke(obj, value);
                }
            }
        }
        return obj;
    }





    /**
     * 文件下载响应头
     *
     * @param response
     * @param request
     * @param fileName
     * @return
     * @throws Exception
     */
    public static HttpServletResponse setResponse(HttpServletResponse response, HttpServletRequest request, String fileName) throws Exception {
        response.setContentType("multipart/form-data;charset=UTF-8");
        //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//br-设置response内容的类型
        //设置下载文件的名称，非ie浏览器默认识别ISO8859-1编码的汉字，若是IE浏览器，则对文件名称进行特殊处理
        if ("IE".equals(CommonUtil.getUserAgent(request))) {
            fileName = URLEncoder.encode(fileName, String.valueOf(StandardCharsets.UTF_8));
        } else {
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);//br-设置头部信息
        return response;

    }

    /***
     * 获取合并规则
     * 此方式用于cpy，后面以这种方式过滤信息和合并
     * @param groupParams 合并规则
     * @param listParams 过滤相同的数据
     * @return 返回合并规则List
     */
    public static List<String> getListByCCpyGroup(List groupParams, List<Map> listParams) {
        //创建合并方式（记录）
        Set<String> groupSets = new HashSet<>();
        //记录每次生成的合并的汇总字符串信息
        StringBuilder groupStr = new StringBuilder();
        for (Map dataItem : listParams) {
            //清空汇总字符串信息
            groupStr.delete(0, groupStr.length());
            //遍历合并规则并生成一个汇总字符串信息保存起来
            for (Object condition : groupParams) {
                groupStr.append(dataItem.get(condition));
            }
            groupSets.add(groupStr.toString());
        }
        groupSets.add(groupStr.toString());
        return new ArrayList<>(groupSets);
    }

    //单条信息的汇总
    public static String getByCCpyGroup(List groupParams, Map param) {
        List<String> listByCCpyGroup = getListByCCpyGroup(groupParams, (param != null && !param.isEmpty()) ? Arrays.asList(param) : Arrays.asList(new HashMap()));
        return listByCCpyGroup.get(0);
    }

    // 判断一个字符是否是中文
    public static boolean isChinese(char c) {
        return c >= 0x4E00 &&  c <= 0x9FA5;// 根据字节码判断
    }
    // 判断一个字符串是否含有中文
    public static boolean isChinese(String str) {
        if (str == null) return false;
        for (char c : str.toCharArray()) {
            if (isChinese(c)) return true;// 有一个中文字符就返回
        }
        return false;
    }
}
